﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Text.RegularExpressions;

using com.globalwave.a8ext;
using Common;

namespace SalePrinting
{
    public partial class OrderPrintingForm : Form
    {
        public OrderPrintingForm()
        {
            InitializeComponent();
        }

        private ExcelApp excelApp;
        private OrderService orderService;
        private OrderDetailService orderDetailService;
        private ProductService productService;
        private DataSet products;
        private DateTime systemDate;
        private String orderId;


        public string author_user = "";

        private void Form1_Load(object sender, EventArgs e)
        {
            
            // init service 
            orderDetailService = OrderDetailService.getInstance();
            orderService = OrderService.getInstance();
            productService = ProductService.getInstance();

            systemDate = DateTime.Now;


            // fill product data
            products = productService.query4OrderPrintint(null, null);

            /*
            ToolTip tip = new ToolTip();
            tip.AutoPopDelay = 0;
            tip.InitialDelay = 0;
            tip.ReshowDelay = 0;
            tip.ShowAlways = true;
            tip.SetToolTip(this.cb_product, "输入关键字按(F1)，可筛选产品");

            tip = new ToolTip();
            tip.AutoPopDelay = 0;
            tip.InitialDelay = 0;
            tip.ReshowDelay = 0;
            tip.ShowAlways = true;
            tip.SetToolTip(this.tb_quantity, "数量");

            tip = new ToolTip();
            tip.AutoPopDelay = 0;
            tip.InitialDelay = 0;
            tip.ReshowDelay = 0;
            tip.ShowAlways = true;
            tip.SetToolTip(this.tb_price, "单价");
            */

            initOrderInputEvent();
            initOrderDetailInputEvent();

            initInput();
        }

        private void bt_save_Click(object sender, EventArgs e)
        {

            if (orderId != null) {
                MessageBox.Show("当前是已经存在的订单，请新增后再作订单保存");
                return;
            }

            if (MessageBox.Show("请确认保存订单？", "保存确认", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }

            if (!checkOrder()) {
                return;
            }

            try
            {
                orderService.save(getOrder(), getOrderDetails());

                this.Focus();// 避免重生复按“保存”
                if (MessageBox.Show("保存成功！是否需要打印", "打印确认", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    print();
                }

                initInput();
                                
            } catch(Exception ex) {

                MessageBox.Show("保存失败！！-- " + ex.Message);
                

            }
        }

        private bool checkOrder() {

            if (this.tb_order_number.Text == "0")
            {
                this.tb_order_number.Focus();
                MessageBox.Show("请修改订单编号后再保存！");
            }

            try
            {
                int.Parse(this.tb_order_number.Text);
            }
            catch
            {
                MessageBox.Show("订单编号必须为数字！");
                this.tb_order_number.Focus();
                return false;
            }
            try
            {
                int.Parse(this.tb_creditAoumt1.Text);
            }
            catch
            {
                MessageBox.Show("刷卡1必须为数字！");
                this.tb_creditAoumt1.Focus();
                return false;
            }
            try
            {
                int.Parse(this.tb_creditAoumt2.Text);
            }
            catch
            {
                MessageBox.Show("刷卡2必须为数字！");
                this.tb_creditAoumt2.Focus();
                return false;
            }
            if (this.tb_sale_man.Text == "")
            {
                MessageBox.Show("销售员必须为输入！");
                this.tb_sale_man.Focus();
                return false;
            }
            if (this.tb_order_man.Text == "")
            {
                MessageBox.Show("下单员必须为输入！");
                this.tb_order_man.Focus();
                return false;
            }
            return true;
        }


        private NameValueCollection getOrder()
        {

            NameValueCollection order = new NameValueCollection();
            order.Add("order_number", this.tb_order_number.Text);
            order.Add("order_date", this.tb_orderDate.Text);
            order.Add("process_date", systemDate.ToShortDateString());
            order.Add("process_time", DateTime.Now.ToLongTimeString());
            order.Add("customer_", this.tb_customer.Text);
            order.Add("phone1", this.tb_phone1.Text);
            order.Add("phone2", this.tb_phone2.Text);
            order.Add("address_", this.tb_address.Text);
            order.Add("status_", this.cb_orderStatus.Text);
            order.Add("amount_", this.tb_amount.Text);
            order.Add("sale_man", this.tb_sale_man.Text);
            order.Add("order_man", this.tb_order_man.Text);
            order.Add("warehouse_", this.cb_warehouse.Text);
            order.Add("is_invoice", this.cb_isInvoice.Checked?"Y":"N");
            order.Add("credit_amount_1", this.tb_creditAoumt1.Text);
            order.Add("credit_amount_2", this.tb_creditAoumt2.Text);
            order.Add("cash_amount", this.tb_cashAmount.Text);
            order.Add("remark_", this.tb_remark.Text);
            order.Add("is_allowance", this.cb_isAllowance.Checked ? "Y" : "N");
            order.Add("is_old_2_new", this.cb_isOld2New.Checked ? "Y" : "N");

            return order;
        
        }


        private void setOrder(DataRow order)
        {
            orderId = order["order_id"].ToString();

            this.tb_order_number.Text = order["order_number"].ToString();
            this.tb_orderDate.Text = order["order_date"].ToString();
            this.tb_customer.Text = order["customer_"].ToString();
            this.tb_phone1.Text = order["phone1"].ToString();
            this.tb_phone2.Text = order["phone2"].ToString();
            this.tb_address.Text = order["address_"].ToString();
            this.cb_orderStatus.SelectedItem = order["status_"].ToString();
            this.tb_amount.Text = order["amount_"].ToString();
            this.l_amountUpper.Text = U.toChineseUpper(double.Parse(this.tb_amount.Text));
            this.tb_sale_man.Text = order["sale_man"].ToString();
            this.tb_order_man.Text = order["order_man"].ToString();
            this.cb_warehouse.SelectedItem = order["warehouse_"].ToString();
            this.cb_isInvoice.Checked = (order["is_invoice"].ToString() == "Y");
            this.tb_creditAoumt1.Text = order["credit_amount_1"].ToString();
            this.tb_creditAoumt2.Text = order["credit_amount_2"].ToString();
            this.tb_cashAmount.Text = order["cash_amount"].ToString();
            this.tb_remark.Text = order["remark_"].ToString();
            this.cb_isAllowance.Checked = (order["is_allowance"].ToString() == "Y");
            this.cb_isOld2New.Checked = (order["is_old_2_new"].ToString() == "Y");


        }


        private NameValueCollection[] getOrderDetails()
        {
            if (this.dg_details.Rows == null || this.dg_details.Rows.Count == 0) {
                throw new Exception("没有明细");
            }

            NameValueCollection[] result = new NameValueCollection[this.dg_details.Rows.Count];

            foreach (DataGridViewRow row in this.dg_details.Rows)
            {

                result[row.Index] = new NameValueCollection(); ;
                NameValueCollection order = result[row.Index];
                order.Add("product_code", getCellValueString(row,0));
                order.Add("product_name", getCellValueString(row, 1));
                order.Add("unit_", getCellValueString(row, 2));
                order.Add("quantity_", getCellValueString(row, 3));
                order.Add("price_", getCellValueString(row, 4));
                order.Add("amount_", getCellValueString(row, 5));
                order.Add("maintain_time", getCellValueString(row, 6));
                order.Add("author_user_id", getCellValueString(row, 7));
                
            }

            return result;

        }


        private void setOrderDetails(DataRowCollection details)
        {
            this.dg_details.Rows.Clear();

            foreach (DataRow detail in details)
            {

                int n = dg_details.Rows.Add();

                dg_details.Rows[n].Cells[0].Value = detail["product_code"].ToString();
                dg_details.Rows[n].Cells[1].Value = detail["product_name"].ToString();

                dg_details.Rows[n].Cells[2].Value = detail["unit_"].ToString();
                dg_details.Rows[n].Cells[3].Value = detail["quantity_"].ToString();

                dg_details.Rows[n].Cells[4].Value = detail["price_"].ToString();
                dg_details.Rows[n].Cells[5].Value = detail["amount_"].ToString();

                dg_details.Rows[n].Cells[6].Value = detail["maintain_time"].ToString();
                dg_details.Rows[n].Cells[7].Value = detail["author_user_id"].ToString();

            }

        }


        private String getCellValueString(DataGridViewRow row, int cellIndex) {
            object value = row.Cells[cellIndex].Value;
            if (value == null)
            {
                return "";
            }
            else {
                return value.ToString();
            }
        }

        private void bt_print_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否进行打印？", "打印确认", MessageBoxButtons.YesNo) == DialogResult.No) {
                return;
            }
            print();
        }

        private void print() {

            if (this.dg_details.Rows.Count == 0) {
                MessageBox.Show("没有订单明细，无法打印！");
                return;
            }

            if (excelApp == null)
            {
                excelApp = new ExcelApp();
            }

            excelApp.open(".//template//order_printing.xls");

            // head
            excelApp.excelOut(this.tb_customer.Text + " " + this.tb_phone1.Text + " " + this.tb_phone2.Text, 2, 2);
            excelApp.excelOut(this.tb_address.Text, 3, 2);

            excelApp.excelOut(this.tb_order_number.Text, 2, 6);

            DateTime orderDate = this.tb_orderDate.Value;
            excelApp.excelOut("   " +
                (orderDate.Year % 100).ToString() + "  " +
                 orderDate.Month.ToString().PadLeft(3, ' ') + "  " +  
                 orderDate.Day.ToString().PadLeft(3, ' '), 3, 6);

            // details 
            foreach (DataGridViewRow row in this.dg_details.Rows)
            {
                excelApp.excelOut(
                    new String[]{
                        //getCellValueString(row, 0),
                        getCellValueString(row, 1),
                        getCellValueString(row, 2),
                        getCellValueString(row, 3),
                        getCellValueString(row, 4),
                        //getCellValueString(row, 5),
                        getCellValueString(row, 6)},
                    row.Index,
                    false);
            }

            // foot
            /*
            string amount_upper = "" ;
            int strLen = this.l_amountUpper.Text.Length ;
            for (int i = 0 ; i < strLen ; i ++) {
                if (i%2 == 0) {
                    amount_upper += "　" ;
                } else {
                    amount_upper = this.l_amountUpper.Text.Substring(strLen - i - 1, 1) + amount_upper;
                }
            }*/
            excelApp.excelOut(U.toChineseUpper4Print(double.Parse(this.tb_amount.Text)), 11, 2);
            excelApp.excelOut("￥" + this.tb_amount.Text, 11, 6);

            excelApp.excelOut(this.tb_sale_man.Text, 14, 2);
            excelApp.excelOut(this.tb_sale_man.Text, 14, 6);

            // remark
            int rowOffset = 0;
            if (this.cb_isInvoice.Checked)
            {
                excelApp.excelOut(this.cb_isInvoice.Text, 6 + (rowOffset ++), 7);
            }

            if (this.tb_creditAoumt1.Text != "0")
            {
                excelApp.excelOut("刷卡1:" + this.tb_creditAoumt1.Text, 6 + (rowOffset++), 7);
            }
            if (this.tb_creditAoumt2.Text != "0")
            {
                excelApp.excelOut("刷卡2:" + this.tb_creditAoumt2.Text, 6 + (rowOffset++), 7);
            }
            if (this.cb_isAllowance.Checked)
            {
                excelApp.excelOut(this.cb_isAllowance.Text, 6 + (rowOffset++), 7);
            }
            if (this.cb_isOld2New.Checked)
            {
                excelApp.excelOut(this.cb_isOld2New.Text, 6 + (rowOffset++), 7);
            }
            excelApp.printAndClose(".//template//order_printing.preview.xls");
        }

        private void Form_Order_Leave(object sender, EventArgs e)
        {

            if (excelApp != null)
            {
                excelApp.quitNotSave();
            }
        }


        private void bt_addDetail_Click(object sender, EventArgs e)
        {
            Object productCode = this.cb_product.SelectedValue;

            if (productCode == null || productCode.ToString() == "")
            {
                MessageBox.Show("请筛选产品后选择你所需要的！");
                this.cb_product.Focus();
                return;
            }

            if (String.IsNullOrEmpty(cb_unit.SelectedItem as String))
            {
                MessageBox.Show("单位不能为空！");
                cb_unit.Focus();
                return;
            }

            /*
            if (String.IsNullOrEmpty(cb_maintainTime.SelectedItem as String))
            {
                MessageBox.Show("维修时间不能为空！");
                cb_maintainTime.Focus();
                return;
            }*/


            try
            {
                double.Parse(this.tb_quantity.Text);
            }
            catch {
                MessageBox.Show("数量需为数字");
                this.tb_quantity.Focus();
                return;
            }

            try
            {
                double.Parse(this.tb_price.Text);
            }
            catch
            {
                MessageBox.Show("单价需为数字");
                this.tb_price.Focus();
                return;
            }

            DataRowView productRow = (cb_product.SelectedItem as DataRowView) ;


            double lowPrice = double.Parse(productRow["lowestprice"].ToString());
            double highPrice = double.Parse(productRow["retailprice"].ToString());
            double price = double.Parse(this.tb_price.Text);
            double price2 = double.Parse(productRow["price"].ToString());
            string X_F = "赠品";
            string product2 = this.cb_product.Text;
            
            // 授权规则
            bool isAuthor = (lowPrice != 0 && lowPrice > price || highPrice != 0 && highPrice < price) && X_F.IndexOf(product2) == -1 ;

            if (isAuthor)
            {
                Form authorForm = new AuthorForm(this, productRow, this.tb_price.Text);
                authorForm.ShowDialog();

                if (authorForm.DialogResult == DialogResult.Cancel)
                {
                    MessageBox.Show("授权不通过！");
                    return;
                }
            }

            int n = dg_details.Rows.Add();

            dg_details.Rows[n].Cells[0].Value = productRow["usercode"].ToString();
            dg_details.Rows[n].Cells[1].Value = productRow["fullname"].ToString();

            dg_details.Rows[n].Cells[2].Value = (cb_unit.SelectedItem as String);
            dg_details.Rows[n].Cells[3].Value = this.tb_quantity.Text;

            dg_details.Rows[n].Cells[4].Value = this.tb_price.Text;
            dg_details.Rows[n].Cells[5].Value = double.Parse(this.tb_quantity.Text) * double.Parse(this.tb_price.Text);

            dg_details.Rows[n].Cells[6].Value = (cb_maintainTime.SelectedItem as String);

            if (isAuthor)
            {
                dg_details.Rows[n].Cells[7].Value = author_user;
            }
            else
            {
                dg_details.Rows[n].Cells[7].Value = "";
            }

            sumTotal();

            initOrderDetailInput();

            this.cb_product.Focus();
        }

        private void dg_details_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            removeSeletedDetail();
        }

        private void removeSeletedDetail() {

            int removeRow = -1 ;

            if (this.dg_details.SelectedRows != null
                    && this.dg_details.SelectedRows.Count != 0)// last row can't be deleted
            {
                removeRow = this.dg_details.SelectedRows[0].Index ;
            }

            if (this.dg_details.SelectedCells != null
                    && this.dg_details.SelectedCells.Count != 0)// last row can't be deleted
            {
                removeRow = this.dg_details.SelectedCells[0].OwningRow.Index;
            }

            if (removeRow == -1) {
                return;
            }
            
            
            this.dg_details.Rows.RemoveAt(removeRow);
        }

        private void sumTotal() {
            double result = 0 ; 
            for (int i = 0; i < dg_details.Rows.Count; i++) {
                result += double.Parse(dg_details.Rows[i].Cells[5].Value.ToString());
            
            }

            this.tb_amount.Text = result.ToString();

            l_amountUpper.Text = U.toChineseUpper(result);

            this.tb_cashAmount.Text = (result - double.Parse(this.tb_creditAoumt1.Text) - double.Parse(this.tb_creditAoumt2.Text)).ToString();

            setCashAmount();
        }


        private void find(string order_number, int offSet)
        {
            if (order_number == "" && offSet == 0)
            {
                MessageBox.Show("订单编号必须输入！");
                return;
            }

            OrderService orderService = OrderService.getInstance();

            NameValueCollection where = new NameValueCollection() ;

            if (offSet == 0)
            {
                where.Add("order_number", order_number);
            }
            else {
                long id = -1;
                //where.Add("order_number", (long.Parse(order_number) + offSet).ToString());
                if (String.IsNullOrEmpty(this.orderId))
                {
                    if (MessageBox.Show("当前为打单状态，是否要续约查询？", "查询确认", MessageBoxButtons.YesNo) == DialogResult.No) {
                        return;
                    }

                    id = orderService.getMaxOrderId(systemDate);

                    if (id == -1)
                    {
                        MessageBox.Show("未找到订单记录！");
                        return;
                    }
                }
                else { 
                    id = long.Parse(this.orderId) + offSet ;
                }

                where.Add("order_id", id.ToString());
                where.Add("process_date", systemDate.ToShortDateString());// 只能查当天的单
            }

            DataTable orderTable = orderService.query("select * from [order] ", -1, where).Tables[0];

            if (orderTable.Rows.Count == 0)
            {
                MessageBox.Show("未找到订单记录！");
                return;
            }

            DataRow row = orderTable.Rows[0] ;

            setOrder(row);

            where = new NameValueCollection();
            where.Add("order_id", row["order_id"].ToString());

            DataTable orderDetailTable = orderService.query("select * from [order_detail] ", -1, where).Tables[0];

            setOrderDetails(orderDetailTable.Rows);
        }


        private void initInput()
        {
            orderId = null;

            this.dg_details.Rows.Clear();
            initOrderDetailInput();
            initOrderInput();

            if (this.tb_order_number.Text == "0")
            {
                this.tb_order_number.Focus();
                //MessageBox.Show("请修改订单编号后再打单！");
            }
            else {
                //tb_order_number.Enabled = false;
                this.ActiveControl = this.tb_customer;
                this.tb_customer.Focus();
            }
        }

        private void initOrderDetailInput()
        {
            initComboBox(cb_product, new string[] { }, "");
            this.cb_product.DataSource = products.Tables[0];
            this.cb_product.DisplayMember = "fullname";
            this.cb_product.ValueMember = "usercode";
            //this.cb_product.BeginUpdate();
            //this.cb_product.DataSource = new DataTable();
            //this.cb_product.EndUpdate();
            this.cb_product.Text = "";
            this.cb_product.SelectedValue = "";

            tb_quantity.Text = "";
            tb_price.Text = "";


            initComboBox(cb_unit, new string[] { "台","个", "米", "套" }, "台");
            initComboBox(cb_maintainTime, new string[] {"凭保修卡", "保修两年", "保修一年", "保修半年", "保修三个月", "保修七日", "不保修" }, "保修一年");

        }

        private void initOrderDetailInputEvent()
        {
            this.cb_product.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

            this.tb_quantity.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

            this.tb_price.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

            this.cb_unit.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

            this.cb_maintainTime.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);
        }

        private void initOrderInput()
        {
            /*
            if (string.IsNullOrEmpty(tb_order_number.Text))
            {
                tb_order_number.Text = orderService.getNextOrderNumber(systemDate).ToString();
            }
            else
            {
                tb_order_number.Text = (int.Parse(tb_order_number.Text) + 1).ToString();
            }*/
            tb_order_number.Text = orderService.getNextOrderNumber(systemDate).ToString();
            
            l_systemTime.Text = systemDate.ToShortDateString();
  

            initComboBox(cb_orderStatus, new string[] { "正常", "作废", "作单" }, "正常");
            
            tb_orderDate.Value = systemDate;

            tb_customer.Text = "";
            tb_phone1.Text = "";
            tb_phone2.Text = "";
            
            tb_address.Text = "";

            initComboBox(cb_warehouse, new string[] { "仓库", "铺面" }, "仓库");
            
            tb_sale_man.Text = "";
            
            tb_order_man.Text = "";
            
            this.cb_isInvoice.Checked = false;
            
            tb_creditAoumt1.Text = "0";

            tb_creditAoumt2.Text = "0";

            tb_cashAmount.Text = "0";

            tb_amount.Text = "0";

            l_amountUpper.Text = "";

            tb_remark.Text = "";

            this.cb_isAllowance.Checked = false;
            this.cb_isOld2New.Checked = false;
        }

        private void initOrderInputEvent()
        {
            this.tb_order_number.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);
            this.tb_order_number.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.numberAccpter);

            this.cb_orderStatus.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

            this.tb_orderDate.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

            this.tb_customer.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);
            this.tb_phone1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);
            this.tb_phone2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

            this.tb_address.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

            this.tb_amount.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

            this.cb_warehouse.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

            this.tb_sale_man.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

            this.tb_order_man.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

            this.cb_isInvoice.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

            this.tb_creditAoumt1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);
            this.tb_creditAoumt1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.numberAccpter);

            this.tb_creditAoumt2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);
            this.tb_creditAoumt2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.numberAccpter);

            this.tb_remark.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);
            
            this.cb_isAllowance.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);
            this.cb_isOld2New.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.enter2TabEventHandle_KeyPress);

        }

        private void initComboBox(ComboBox box, string[] values, string defaultValue) {
            if (box.Items.Count == 0) {
                box.BeginUpdate() ;
                foreach (string value in values) {
                    box.Items.Add(value);
                }
                box.EndUpdate() ;
            }

            box.SelectedItem = defaultValue ;
        }

        private void enter2TabEventHandle_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (int)Keys.Enter)
            {
                SendKeys.Send("{TAB}");
            }

        }
        
        private void numberAccpter(object sender, KeyPressEventArgs e) {
            int keyValue = (int)e.KeyChar;
            if ((keyValue >= 48 && keyValue <= 57) || keyValue == 8 || keyValue == 46)
            {
                if (sender != null && sender is TextBox && keyValue == 46)
                {
                    if (((TextBox)sender).Text.IndexOf(".") >= 0)
                        e.Handled = true;
                    else
                        e.Handled = false;
                }
                else
                    e.Handled = false;
            }
            else
                e.Handled = true;
        }

        private void tb_creditAoumt_TextChanged(object sender, EventArgs e)
        {
            setCashAmount();
        }


        private void setCashAmount()
        {
            this.tb_cashAmount.Text =
                (parseDouble(this.tb_amount.Text)
                        - parseDouble(this.tb_creditAoumt1.Text)
                        - parseDouble(this.tb_creditAoumt2.Text)).ToString();
        }

        private double parseDouble(string str) {
            if (string.IsNullOrEmpty(str))
            {
                return 0;
            }
            else {
                return double.Parse(str);
            }
        }

        private DataSet filter(DataSet src, String filterValue)
        {

            DataSet dataSet = new DataSet();
            dataSet.Tables.Add(src.Tables[0].Clone()) ;
            DataTable dataTable = dataSet.Tables[0];

            /*
            foreach (DataColumn c in src.Tables[0].Columns)
            {
                DataColumn cNew = new DataColumn();
                cNew.ColumnName = c.ColumnName;
                cNew.DataType = c.DataType;
                dataTable.Columns.Add(cNew);
                //Debug.WriteLine(c.ColumnName+"--"+c.DataType);
            }*/

            DataRow[] rows = src.Tables[0].Select(" fullname like '%" + filterValue  + "%' ");
           
            foreach (DataRow r in rows)
            {
                DataRow newRow = dataTable.NewRow();
                newRow.ItemArray = r.ItemArray;

                dataTable.Rows.Add(newRow);
            }

            Console.Write(dataSet.GetXml());

            return dataSet;
        }


        private void cb_product_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode != Keys.F1)
            {
                return;
            }

            if (this.cb_product.Text.Length < 2) {
                MessageBox.Show("必须多于两个字才能筛选产品！");
                return;
            }

            ComboBox cb = sender as ComboBox;

            this.cb_product.BeginUpdate();
            this.cb_product.DataSource = filter(products, cb.Text).Tables[0];
            this.cb_product.EndUpdate();
            this.cb_product.DroppedDown = true;
        }

        private void dg_details_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                removeSeletedDetail();
            }
            else if (e.KeyCode == Keys.Enter){
                this.cb_product.Focus();
            }


            
            
        }
        
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {

            if (keyData == Keys.F9)
            {
                this.dg_details.Focus();
            }
                /*
            else if (keyData == Keys.F3)
            {
                bt_preview.PerformClick();
                //bt_preview_Click(null, null);
            }
            else if (keyData == Keys.F4)
            {
                bt_next.PerformClick();
                //bt_next_Click(null, null);
            }
            else if (keyData == Keys.F5)
            {
                bt_find.PerformClick();
                //bt_find_Click(null, null);
            }*/

            return base.ProcessCmdKey(ref msg, keyData);
        }
        
        private void bt_add_Click(object sender, EventArgs e)
        {
            initInput();

            enableAllInput(true);
        }

        private void bt_find_Click(object sender, EventArgs e)
        {
            find(this.tb_order_number.Text, 0);


            if (!String.IsNullOrEmpty(this.orderId)) {
                enableAllInput(false);
            }
        }

        private void bt_next_Click(object sender, EventArgs e)
        {
            find(this.tb_order_number.Text, 1);


            if (!String.IsNullOrEmpty(this.orderId))
            {
                enableAllInput(false);
            }
        }

        private void bt_preview_Click(object sender, EventArgs e)
        {
            find(this.tb_order_number.Text, -1);


            if (!String.IsNullOrEmpty(this.orderId))
            {
                enableAllInput(false);
            }
        }

        private void bt_delete_Click(object sender, EventArgs e)
        {
            updateOrderStatus("作废");
        }

        private void updateOrderStatus(string status) {
            try
            {

                if (string.IsNullOrEmpty(this.orderId)) {
                    MessageBox.Show("没有订单记录可以更新状态，或新增订单未保存，不能更新状态！");
                    return;
                }
            
                if (MessageBox.Show("是否确认更改单据状态？", "更改确认", MessageBoxButtons.YesNo) == DialogResult.No) {
                return;
                }
                
                NameValueCollection order = new NameValueCollection();
                order.Add("order_id", this.orderId);
                order.Add("status_", status);

                this.orderService.update(order);

                this.cb_orderStatus.SelectedItem = status;

                MessageBox.Show("成功更新订单状态至\"" + status + "\"");

            }
            catch (Exception ex) {

                MessageBox.Show("更新订单状态失败！--" + ex.Message);
            }
        }

        private void bt_order_Click(object sender, EventArgs e)
        {

            updateOrderStatus("作单");
        }

        private void bt_dataDelete_Click(object sender, EventArgs e)
        {
            try
            {
               
                if (MessageBox.Show("确认删除当天["+systemDate.ToShortDateString()+"]之前的所有订单数据", "删除确认", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }
                int count = this.orderService.clearHistory(systemDate);
                MessageBox.Show("成功删除数据" + count + "条！");
            } catch (Exception ex) {
                MessageBox.Show("删除数据失败!--" + ex.Message);
            }
        }

    
        private void timer1_Tick(object sender, EventArgs e)
        {

            label20.Text = DateTime.Now.ToString("T");
 //           label4.Text = cb_orderStatus.Text ;
 //           if (cb_orderStatus.Text  == "正常")
 //           { label4.ForeColor = Color.Cyan ;
 //           label4.Text = "正    常";
 //           }
 //           else
 //           { label4.ForeColor = Color.Red ;
 //           if (cb_orderStatus.Text  == "作单")
 //           { label4.Text = "作    单"; }
 //           else
 //           { label4.Text = "作    废"; }
 //           }
            
        }



        private void cb_orderStatus_TextChanged(object sender, EventArgs e)
        {
            if (cb_orderStatus.Text == "正常")
            {
                label4.ForeColor = Color.Cyan;
                label4.Text = "正    常";
            }
            else
            {
                label4.ForeColor = Color.Red;
                if (cb_orderStatus.Text == "作单")
                {
                    label4.Text = "作    单"; 
                }
                else
                {
                    label4.Text = "作    废"; 
                }
            }
        }


        private void enableAllInput(Boolean isAble) {
            foreach (Control ctrl in this.Controls)
            {
                if (ctrl is ComboBox)
                {
                    ((System.Windows.Forms.ComboBox)ctrl).Enabled = isAble;
                }
                else if (ctrl is TextBox)
                {
                    ((System.Windows.Forms.TextBox)ctrl).Enabled = isAble;
                }
                else if (ctrl is CheckBox)
                {
                    ((System.Windows.Forms.CheckBox)ctrl).Enabled = isAble;
                }
            }

            this.bt_addDetail.Enabled = isAble;
            this.tb_order_number.Enabled = true;
        }

        private void cb_product_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataRowView row = (DataRowView)cb_product.SelectedItem;

            if (row == null) {
                return;
            }
            cb_unit.SelectedItem = row["expr2"].ToString();
            cb_maintainTime.SelectedItem = row["field1"].ToString();
        }




        private void outputSummaryExcel()
        {

            if (excelApp == null)
            {
                excelApp = new ExcelApp();
            }

            excelApp.open(".//template//sumarry_report.xls");

            NameValueCollection where = new NameValueCollection();

            where.Add("process_date", systemDate.ToShortDateString());// 只能查当天的单

            excelApp.excelOut("万顷沙汇总表（" + systemDate.ToShortDateString() + "）", 1, 1);

            // details 
            DataTable table = orderService.query("SELECT * FROM Fee_Payout WHERE type_='P' ", -1, where).Tables[0];

            int rowIndex = 2;
            int cellIndex = 2;
            foreach (DataRow detail in table.Rows)
            {
                excelApp.excelOut(detail["name_"].ToString() + "-" + detail["amount_"].ToString(), rowIndex, cellIndex++);
            }

            table = orderService.query("SELECT * FROM Fee_Payout WHERE type_='F' ", -1, where).Tables[0];

            rowIndex = 3;
            cellIndex = 2;
            foreach (DataRow detail in table.Rows)
            {

                excelApp.excelOut(detail["name_"].ToString() + "-" + detail["amount_"].ToString(), rowIndex, cellIndex++);

            }


            table = orderService.query("SELECT d.*, o.*, d.amount_ as amount_detail, o.amount_ as amount_order FROM [Order] o INNER JOIN Order_Detail d ON o.order_id = d.order_id ", -1, where).Tables[0];

            rowIndex = 5;
            foreach (DataRow detail in table.Rows)
            {

                cellIndex = 1;
                excelApp.excelOut(detail["product_name"].ToString(), rowIndex, cellIndex++);
                excelApp.excelOut(detail["sale_man"].ToString(), rowIndex, cellIndex++);
                excelApp.excelOut(detail["quantity_"].ToString(), rowIndex, cellIndex++);
                excelApp.excelOut(detail["price_"].ToString(), rowIndex, cellIndex++);
                excelApp.excelOut(detail["amount_order"].ToString(), rowIndex, cellIndex++);
                excelApp.excelOut(detail["warehouse_"].ToString(), rowIndex, cellIndex++);
                
                string remark = "";
                if (detail["is_invoice"].ToString() == "Y")
                {
                    remark += "发票\n";
                }
                if (detail["credit_amount_1"].ToString() == "1")
                {
                    remark += "刷卡1\n";
                }
                if (detail["credit_amount_2"].ToString() == "1")
                {
                    remark += "刷卡2\n";
                }
                if (detail["is_allowance"].ToString() == "Y")
                {
                    remark += "下乡补贴\n";
                }
                if (detail["is_old_2_new"].ToString() == "Y")
                {
                    remark += "以旧换新\n";
                }
                if (detail["author_user_id"].ToString() != "")
                {
                    remark += "价格审批\n";
                }
                excelApp.excelOut(remark, rowIndex, cellIndex++);

                excelApp.excelOut(detail["author_user_id"].ToString(), rowIndex, cellIndex++);

                excelApp.excelOut(detail["order_number"].ToString(), rowIndex, cellIndex++);

                rowIndex++;

            }


            table = orderService.query("SELECT sum(credit_amount_1) as credit_amount_1, sum(credit_amount_2) as credit_amount_2, sum(cash_amount) as cash_amount, sum(amount_) as amount_ FROM [Order] ", -1, where).Tables[0];

            rowIndex++;

            rowIndex++;

            rowIndex++;

            cellIndex = 4;

            foreach (DataRow detail in table.Rows)// only one row
            {

                excelApp.excelOut("销售总额：", rowIndex, cellIndex);
                excelApp.excelOut(detail["amount_"].ToString(), rowIndex++, cellIndex + 1);

                excelApp.excelOut("刷卡1：", rowIndex, cellIndex);
                excelApp.excelOut(detail["credit_amount_1"].ToString(), rowIndex++, cellIndex+1);

                excelApp.excelOut("刷卡2：", rowIndex, cellIndex);
                excelApp.excelOut(detail["credit_amount_2"].ToString(), rowIndex++, cellIndex+1);

                excelApp.excelOut("当天现金：", rowIndex, cellIndex);
                excelApp.excelOut(detail["cash_amount"].ToString(), rowIndex++, cellIndex+1);

                rowIndex++;

            }


            table = orderService.query("SELECT sum(amount_) as amount_ FROM Fee_Payout WHERE type_='P' ", -1, where).Tables[0];

            //rowIndex = 5;
            foreach (DataRow detail in table.Rows)// only one row
            {
                excelApp.excelOut("费用：", rowIndex, cellIndex);
                excelApp.excelOut(detail["amount_"].ToString(), rowIndex++, cellIndex + 1);
            }

            table = orderService.query("SELECT sum(amount_) as amount_ FROM Fee_Payout WHERE type_='F' ", -1, where).Tables[0];

            //rowIndex = 5;
            foreach (DataRow detail in table.Rows)// only one row
            {
                excelApp.excelOut("其他收入：", rowIndex, cellIndex);
                excelApp.excelOut(detail["amount_"].ToString(), rowIndex++, cellIndex+1);
            }

            excelApp.saveAndClose(".//template//sumarry_report.preview.xls");
        }

        private void bt_sumary_Click(object sender, EventArgs e)
        {
            outputSummaryExcel();
        }
    }
    
}
